$( function() {

    var readUrl   = 'index.php/home/read',
        updateUrl = 'index.php/home/update',
        delUrl    = 'index.php/home/delete',
        readPatient    = 'index.php/home/readPatient',
        listadoPremios    = 'index.php/home/listadoPremios',
        delHref,
        updateHref,
        updateId;

	$("ul li a").css("cursor", "pointer");
    
        $( '#tabs' ).tabs({
            fx: {height: 'toggle', opacity: 'toggle'}
        });

	$("a[href*='read']").click(function(evt) {
    	$.ajax({
    	    url: readUrl,
    	    dataType: 'json',
    	    success: function( response ) {
    	        for( var i in response ) {
    	            response[ i ].updateLink = updateUrl + '/' + response[ i ].regkey;
    	            response[ i ].deleteLink = delUrl + '/' + response[ i ].regkey;
    	        }
    	        $("#records").empty(); /*esto limpiará la tabla antes de agregar los registros nuevos*/
    	        $('#readTemplate').render(response).appendTo("#records");
    	    }
    	});
	}).click();

	$("a[href*='listadoPremios']").click(function(evt) {
		//$('#ajaxLoadAni').fadeIn( 'slow' );
		$.ajax({
			url: listadoPremios,
			dataType: 'json',
			success: function( response ) {
				if (response != null) {
					$("#recordsListadoPremios").empty(); /*esto limpiará la tabla antes de agregar los registros nuevos*/
					$('#listadoPremiosTemplate').render(response).appendTo("#recordsListadoPremios");

					$("#listadoPremios :button[value=\"Eliminar\"]").click(function(evt){
						var tr = $(this).parents("tr[id]");
						var id = tr.attr("id");

						var ajaxUrl = 'index.php/home/deletePremio/' + id;
						$.ajax({
							url: ajaxUrl,
							dataType: 'json',
							success: function( response ) {
								if (response.success) {
									tr.remove();
								} else {
									alert(response.msg);
								}
							}
						});
					});

					$("#listadoPremios :button[value=\"Actualizar Ganadora\"]").click(function(evt){
						var tr = $(this).parents("tr[id]");
						var id = tr.attr("id");
						var winnerName = $(":text[name='winner_name-" + id + "']").val();

						var ajaxUrl = 'index.php/home/updateWinner/'
							+ id + '/' + winnerName;
						$.ajax({
							url: ajaxUrl,
							dataType: 'json',
							success: function( response ) {
								if (response.success) {
									alert("Cambio exitoso");
								} else {
									alert(response.msg);
								}
							}
						});
					});
				}
			}
		});
	});
    
	$("a[href*='lpatient']").click(function(evt) {
    	$.ajax({
    	    url: readPatient,
    	    dataType: 'json',
    	    success: function( response ) {
				if (response != null) {
					$("#recordsPatient").empty(); /*esto limpiará la tabla antes de agregar los registros nuevos*/
					$('#readTemplatePatients').render(response).appendTo("#recordsPatient");
				}
    	    }
    	});
	});
    
    $( '#msgDialog' ).dialog({
        autoOpen: false,
        
        buttons: {
            'Ok': function() {
                $( this ).dialog( 'close' );
            }
        }
    });
    
    $( '#updateDialog' ).dialog({
        autoOpen: false,
        buttons: {
            'Update': function() {
//                $( '#ajaxLoadAni' ).fadeIn( 'slow' );
                $( this ).dialog( 'close' );
                $.ajax({
                    url: updateHref,
                    type: 'POST',
                    data: $( '#updateDialog form' ).serialize(),
                    success: function( response ) {
                        $( '#msgDialog > p' ).html( response );
                        $( '#msgDialog' ).dialog( 'option', 'title', 'Success' ).dialog( 'open' );
                        var name = $( 'tr#' + updateId + ' td' )[ 1 ];
                        var email = $( 'tr#' + updateId + ' td' )[ 2 ];
                        $( name ).html( $( '#name' ).val() );
                        $( name ).html( $( '#last_name' ).val() );
                        $( name ).html( $( '#login' ).val() );
                        $( name ).html( $( '#password' ).val() );
                        $( email ).html( $( '#email' ).val() );
                        $( '#updateDialog form input' ).val( '' );
                        
                    } //end success
                    
                }); //end ajax()
            },
            
            'Cancel': function() {
                $( this ).dialog( 'close' );
            }
        },
        width: '350px'
    }); //end update dialog
    
    $( '#delConfDialog' ).dialog({
        autoOpen: false,
        buttons: {
            'No': function() {
                $( this ).dialog( 'close' );
            },'Yes': function() {
                $( this ).dialog( 'close' );
                $.ajax({
                    url: delHref,
                    success: function( response ) {
                        $( '#msgDialog > p' ).html( response );
                        $( '#msgDialog' ).dialog( 'option', 'title', 'Success' ).dialog( 'open' );
                        $( 'a[href=' + delHref + ']' ).parents( 'tr' )
                        .fadeOut( 'slow', function() {
                            $( this ).remove();
                        });
                        
                    } //end success
                });
            } //end Yes
        } //end buttons
    }); //end dialog
    
    $( '#records' ).delegate( 'a.updateBtn', 'click', function() {
        updateHref = $( this ).attr( 'href' );
        updateId = $( this ).parents( 'tr' ).attr( "id" );
        $.ajax({
            url: 'index.php/home/getById/' + updateId,
            dataType: 'json',
            success: function( response ) {
                $( '#name' ).val( response.name );
                $( '#last_name' ).val( response.last_name );
                $( '#login' ).val( response.login );
                $( '#password' ).val( response.password );
                $( '#email' ).val( response.email );
                $( '#userId' ).val( updateId );
                $( '#updateDialog' ).dialog( 'open' );
            }
        });
        return false;
    }); //end update delegate
    
    $( '#records' ).delegate( 'a.deleteBtn', 'click', function() {
        delHref = $( this ).attr( 'href' );
        $( '#delConfDialog' ).dialog( 'open' );        
        return false;
    
    }); //end delete delegate

	// --- Create Record ---
	$( '#create form' ).submit( function() {
                    $.ajax({
                        url: 'index.php/home/create',
                        type: 'POST',
                        data: $( this ).serialize(),
                        success: function( response ) {

                                $( '#msgDialog > p' ).html( response );
                                $( '#msgDialog' ).dialog( 'option', 'title', 'Success' ).dialog( 'open' );
                                $( 'input', this ).val( '' );
                                $( '#tabs' ).tabs( 'select', 0 );
                        }
                    });
                    
                    $.ajax({
                        url: readUrl,
                        dataType: 'json',
                        success: function( response ) {
                            for( var i in response ) {
                                response[ i ].updateLink = updateUrl + '/' + response[ i ].regkey;
                                response[ i ].deleteLink = delUrl + '/' + response[ i ].regkey;
                            }
                            $("#records").empty(); /*esto limpiará la tabla antes de agregar los registros nuevos*/
                            $('#readTemplate').render(response).appendTo("#records");
                        }
                    });
		return false;
	});

	$("#cFechaSorteo").datepicker({
		"disabled" : false,
		"dateFormat" : "dd-mm-yy"
	});

	$( '#lPremios form' ).submit(function(evt) {
		var cancel = false;
		$("#lPremios :input:not(:submit)").each(function(index, element){
			val = $.trim($(this).val());
			if (!val) {
				cancel = true;
				return;
			}
		});
		evt.preventDefault();
		if (cancel) {
			evt.stopImmediatePropagation();
			alert("Todos los datos son requeridos.");
		}
	});
	
	$( '#lPremios form' ).submit( function() {
		var options = {
			url:       'index.php/home/lPremios',
			dataType:  'json',
			success: function(response) {
				if (response.success) {
					$("#lPremios input:not(:submit)").val("");
				} else {
					alert(response.msg);
				}
			}
		};

		$("#lPremiosForm").ajaxSubmit(options);
		return false;
	});

}); //end document ready